/********************************************************/
/*	Copyright (C) 2016 Gong Li Bin		 	*/
/*	Project:	GlbLib-1.0.0			*/
/*	Author:		gong_libin			*/
/*	Date:		2016_06_01			*/
/*	File:		GlbPool.cpp			*/
/********************************************************/

#include "GlbPool.h"

namespace GlbCls
{

CGlbPool::CGlbPool()
{
	m_usTotal = 0;
	m_usCursor = 0;
	m_pCMember = NULL;
	m_pRoutine = NULL;
	memset(&m_stAttr, '\0', sizeof(pthread_attr_t));
}

CGlbPool::CGlbPool(USHORT usTotal)
{
	m_usCursor = 0;
	m_pRoutine = NULL;
	m_usTotal = usTotal;
	m_pCMember = new CGlbMember[usTotal];
	memset(&m_stAttr, '\0', sizeof(pthread_attr_t));
}

CGlbPool::~CGlbPool()
{
	GlbPoolDestroy();
	delete []m_pCMember;
}

USHORT CGlbPool::GlbPoolTotalGet()
{
	return m_usTotal;
}

void CGlbPool::GlbPoolDestroy()
{
	USHORT usCount = 0;

	for (; usCount < m_usTotal; usCount ++) {
		(m_pCMember + usCount)->GlbThreadDestroy();
	}

	return;
}

int CGlbPool::GlbPoolAttrInit()
{
	if (GLB_SUCCESS != pthread_attr_init(&m_stAttr)) {
		GLB_ERROR("%s\n", strerror(errno));
		return GLB_FAILURE;
	}

	return GLB_SUCCESS;
}

int CGlbPool::GlbPoolCreate()
{
	USHORT usCount = 0;

	for (; usCount < m_usTotal; usCount ++) {
		(m_pCMember + usCount)->GlbThreadRoutineSet(m_pRoutine);
		(m_pCMember + usCount)->GlbThreadAttrSet((void*)&m_stAttr);
		if (GLB_FAILURE == (m_pCMember + usCount)->GlbMemberCreate()) {
			return GLB_FAILURE;
		}
	}

	return GLB_SUCCESS;
}

void CGlbPool::GlbPoolJoin()
{
	USHORT usCount = 0;

	for (; usCount < m_usTotal; usCount ++) {
		(m_pCMember + usCount)->GlbThreadJoin(NULL);
	}

	return;
}

void CGlbPool::GlbPoolRoutineSet(GLB_ROUTINE pRoutine)
{
	m_pRoutine = pRoutine;

	return;
}

void CGlbPool::GlbPoolTotalSet(USHORT usTotal)
{
	m_usTotal = usTotal;
	m_pCMember = new CGlbMember[usTotal];

	return;
}

void CGlbPool::GlbPoolDistribute(void* pPara)
{
	while (GLB_SUCCESS != (m_pCMember + m_usCursor)->GlbMemberAssign(pPara)) {
		if (++ m_usCursor == m_usTotal) {
			m_usCursor = 0;
		}
	}

	return;
}

} /* GlbCls */
